import { api } from '@/services/api';
import type { UserDevice } from '@/services/generated/models';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import { Modal, message, Popconfirm, Button, Space } from 'antd';
import React, { useRef } from 'react';
import { useAccess } from '@umijs/max';

interface DeviceManageModalProps {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  userId?: number;
  onSuccess?: () => void;
}

const DeviceManageModal: React.FC<DeviceManageModalProps> = ({
  visible,
  onVisibleChange,
  userId,
  onSuccess,
}) => {
  const actionRef = useRef<ActionType>();
  const access = useAccess();

  // 表格列定义
  const columns: ProColumns<UserDevice>[] = [
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      search: false,
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      search: false,
    },
    {
      title: '浏览器',
      dataIndex: 'browser',
      search: false,
    },
    {
      title: '操作系统',
      dataIndex: 'os',
      search: false,
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      search: false,
    },
    {
      title: '最后登录',
      dataIndex: 'lastLogin',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      valueEnum: {
        true: { text: '在线', status: 'Success' },
        false: { text: '离线', status: 'Default' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => {
        const actions = [];
        if (record.isActive) {
          if (userId) {
            // 管理员踢出其他用户的设备
            if (access.canLogoutUserDevice) {
              actions.push(
                <Popconfirm
                  key="logout"
                  title="确定要踢出该设备吗？"
                  onConfirm={async () => {
                    try {
                      await api.auth.authDevicesLogoutUserDeviceCreate({
                        id: record.deviceId,
                      });
                      message.success('设备已踢出');
                      actionRef.current?.reload();
                      onSuccess?.();
                    } catch (error) {
                      message.error('操作失败');
                    }
                  }}
                >
                  <a>踢出</a>
                </Popconfirm>,
              );
            }
          } else {
            // 用户踢出自己的设备
            actions.push(
              <Popconfirm
                key="logout"
                title="确定要踢出该设备吗？"
                onConfirm={async () => {
                  try {
                    await api.auth.authDevicesLogoutCreate({
                      id: record.deviceId,
                    });
                    message.success('设备已踢出');
                    actionRef.current?.reload();
                    onSuccess?.();
                  } catch (error) {
                    message.error('操作失败');
                  }
                }}
              >
                <a>踢出</a>
              </Popconfirm>,
            );
          }
        }
        return actions;
      },
    },
  ];

  return (
    <Modal
      title={userId ? '用户设备管理' : '我的设备管理'}
      open={visible}
      onCancel={() => onVisibleChange(false)}
      width={1000}
      footer={null}
      afterOpenChange={(open) => {
        if (open) {
          actionRef.current?.reload();
        }
      }}
    >
      <ProTable<UserDevice>
        headerTitle="设备列表"
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            key="refresh"
            onClick={() => {
              actionRef.current?.reload();
            }}
          >
            刷新
          </Button>,
          ...(userId
            ? access.canLogoutUserAll
              ? [
                  <Popconfirm
                    key="logoutAll"
                    title="确定要踢出该用户的所有设备吗？"
                    onConfirm={async () => {
                      try {
                        await api.auth.authDevicesLogoutUserAllCreate({ userId });
                        message.success('已踢出该用户的所有设备');
                        actionRef.current?.reload();
                        onSuccess?.();
                      } catch (error) {
                        message.error('操作失败');
                      }
                    }}
                  >
                    <Button type="primary" danger>
                      踢出所有设备
                    </Button>
                  </Popconfirm>,
                ]
              : []
            : access.canLogoutUserAll
            ? [
                <Popconfirm
                  key="logoutAll"
                  title="确定要踢出所有设备吗？"
                  onConfirm={async () => {
                    try {
                      await api.auth.authDevicesLogoutAllCreate();
                      message.success('已踢出所有设备');
                      actionRef.current?.reload();
                      onSuccess?.();
                    } catch (error) {
                      message.error('操作失败');
                    }
                  }}
                >
                  <Button type="primary" danger>
                    踢出所有设备
                  </Button>
                </Popconfirm>,
              ]
            : []),
        ]}
        columns={columns}
        request={async () => {
          try {
            const devices = userId
              ? await api.auth.authDevicesList({ userId })
              : await api.auth.authDevicesList();
            return {
              data: devices,
              success: true,
            };
          } catch (error) {
            message.error('获取设备列表失败');
            return {
              data: [],
              success: false,
            };
          }
        }}
        rowKey="deviceId"
        search={false}
        options={false}
      />
    </Modal>
  );
};

export default DeviceManageModal;
